<!--角色管理-->
<template>
  <section class="app-container">
    <div class="content">
      <div class="content-head">
        <el-row>
          <el-col :span="24">
            <el-form :inline="true" :model="queryData" class="demo-form-inline">
              <el-form-item label="关键字">
                <el-input v-model.trim="queryData.roleName" class="width-150" placeholder="请输入角色名称关键字" clearable @keyup.enter.native="getTableList(true)" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="small" icon="el-icon-search" @click="getTableList(true)">查询</el-button>
                <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="reset()">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-button v-p="'roleManageAdd'" type="primary" size="small" icon="el-icon-plus" @click="openDialog('add')">新增角色</el-button>

          </el-col>
          <el-col :span="8" class="text-right">
            <div>
              <el-link icon="fa fa-question-circle-o" @click="help">帮助说明</el-link>
              <!-- <el-button size="small" @click="Utils.building">手动排序</el-button>
              <el-button size="small" @click="Utils.building">按字母排序</el-button> -->
            </div>
          </el-col>
        </el-row>
      </div>
      <!--列表 -->
      <el-table v-loading="tableListLoading" :data="tableList" highlight-current-row height="600" size="small" stripe border>
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column type="index" label="序号" width="46" fixed />
        <el-table-column prop="roleName" label="角色名称" min-width="100" sortable />
        <el-table-column prop="roleCode" label="角色编码" min-width="100" sortable />
        <el-table-column prop="userList" label="人员数量" min-width="100" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.userList.length }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="roleDesc" label="角色描述" min-width="100" sortable show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" min-width="136" sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime | formatDateToStr }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="70" sortable>
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" disabled active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="300" fixed="right">
          <template slot-scope="scope">
            <a v-p="'roleManageAddUser'" href="javascript:;" class="text-blue inline-block" @click="setUser(scope.row)"><i class="el-icon-circle-plus" />添加人员</a>
            <a v-if="scope.row.roleName!=='超级管理员'" v-p="'roleManageUpdate'" href="javascript:;" class="text-blue inline-block" @click="openDialog('edit',scope.row)"><i class="el-icon-edit" />编辑角色</a>
            <a v-if="scope.row.roleName!=='超级管理员'" v-p="'roleManageSetPer'" href="javascript:;" class="text-blue inline-block" @click="setPermission(scope.row)"><i class="el-icon-setting" />设置权限</a>
            <a v-if="scope.row.roleName!=='超级管理员'" v-p="'roleManageIsUse'" href="javascript:;" class="text-blue inline-block" @click="switchStaus(scope.row)"><i class="el-icon-remove" />{{ scope.row.status===1?'停用':'启用' }}角色</a>
            <a v-if="scope.row.roleName!=='超级管理员'" v-p="'roleManageDelete'" href="javascript:;" class="text-danger inline-block" @click="deleteItem(scope.row)"><i class="el-icon-delete" />删除角色</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="element-page clearfix">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100, 500]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-button type="primary" class="pag-go">GO</el-button>
      </div>
    </div>
    <div>
      <!--新增/修改-弹窗  -->
      <el-dialog :title="dialogType=='add'?'新增角色':'修改角色'" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false" @opened="listenOpenedDialog" @closed="listenClosedDialog">
        <el-form ref="dialogFormData" :model="dialogFormData" label-width="160px" :rules="dialogFormDataRules">
          <el-form-item label="角色名称:" prop="roleName">
            <el-input v-model.trim="dialogFormData.roleName" placeholder="请输入角色名称" clearable maxlength="50" />
          </el-form-item>
          <el-form-item label="角色代码:" prop="roleCode">
            <el-input v-model.trim="dialogFormData.roleCode" placeholder="请输入角色代码(英文)" clearable maxlength="50" />
          </el-form-item>
          <el-form-item label="角色描述:" prop="description">
            <el-input v-model.trim="dialogFormData.roleDesc" type="textarea" placeholder="在此输入描述信息" maxlength="300" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogFormDataSubmit('dialogFormData')">立即提交</el-button>
        </div>
      </el-dialog>
      <!--添加人员-弹窗  -->
      <set-user :dialog-prop="setUserVisible" :role-info="roleInfo" :user-list="userList" @getTableList="getTableList" />
      <!--设置权限-弹窗  -->
      <set-permission :dialog-prop="setPermissionVisible" :role-info="roleInfo" />
    </div>
  </section>

</template>

<script>
import { validEnglish } from '@/utils/validate'
import { queryRoleByPage, addRole, updateRole, isUseRole, deleteRole } from '@/api/api'

export default {
  components: {
    'SetUser': () => import(`./RoleSetUser.vue`),
    'SetPermission': () => import(`./RoleSetPermission.vue`)
  },
  data() {
    return {

      currentPage: 1, // 当前页
      total: 0, // 总页数
      pageSize: 20, // 页码
      tableListLoading: false, // 加载loading

      // 查询表单数据
      queryData: {
        roleName: ''
      },

      // 表格数据
      tableList: [],
      // 新增/修改弹窗相关数据
      dialogVisible: false,
      dialogType: 'add',
      // 表单数据
      dialogFormData: {
        roleName: '',
        roleCode: '',
        roleDesc: ''
      },
      // 表单数据验证
      dialogFormDataRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleCode: [
          { validator: validEnglish, trigger: 'blur' }
        ]

      },
      setUserVisible: {
        visible: false
      },
      setPermissionVisible: {
        visible: false
      },
      roleInfo: {
        roleId: null,
        roleName: null
      },
      userList: []

    }
  },
  mounted() {
    this.getTableList(false)
  },
  methods: {
    /**
     * 查询
     * @param {(Boolean)} isFirst  是否从第1页开始查询
     */
    getTableList(isFirst) {
      const params = {
        roleName: this.queryData.roleName,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      if (isFirst) {
        params.pageNum = 1
      }
      this.tableListLoading = true
      queryRoleByPage(params).then(res => {
        this.tableListLoading = false

        if (res.code === '0000') {
          this.total = res.data.total
          this.tableList = res.data.list
        }
      // eslint-disable-next-line handle-callback-err
      }).catch(error => {
        this.tableListLoading = false
      })
    },
    /**
     * 打开新增/编辑弹窗
     * @param {(String)} type  弹窗类型,"add=新增,edit=修改"
     * @param {(Object)} row  操作行数据,修改时传
     */
    openDialog(type, row) {
      this.dialogType = type
      this.dialogVisible = true
      if (type === 'edit') {
        // eslint-disable-next-line no-sequences
        this.dialogFormData.roleId = row.roleId,
        this.dialogFormData.roleName = row.roleName,
        this.dialogFormData.roleCode = row.roleCode,
        this.dialogFormData.roleDesc = row.roleDesc
      }
    },
    listenOpenedDialog() {
    },
    listenClosedDialog() {
      // 初始化表单状态
      this.$refs['dialogFormData'].resetFields()
      this.Utils.emptyObject(this.dialogFormData)
    },
    // 新增编辑弹窗表单提交
    dialogFormDataSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType === 'add') {
            addRole(this.dialogFormData).then(res => {
              if (res.code === '0000') {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.getTableList(true)
                this.$store.dispatch('api/getRoleList')
              }
            }).catch(error => {
              this.$message.error(error)
            })
          } else {
            updateRole(this.dialogFormData).then(res => {
              if (res.code === '0000') {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.getTableList(false)
                this.$store.dispatch('api/getRoleList')
              }
            }).catch(error => {
              this.$message.error(error)
            })
          }
        } else {
          return false
        }
      })
    },
    reset() {
      this.queryData = this.Utils.emptyObject(this.queryData)
    },
    // 添加人员
    setUser(row) {
      this.setUserVisible.visible = true
      this.roleInfo.roleId = row.roleId
      this.roleInfo.roleName = row.roleName
      this.userList = this.Utils.deepCopy(row.userList)
    },
    // 设置权限
    setPermission(row) {
      this.setPermissionVisible.visible = true
      this.roleInfo.roleId = row.roleId
      this.roleInfo.roleName = row.roleName
    },
    switchStaus(row) {
      const params = {
        roleId: row.roleId,
        status: Number(!row.status)
      }
      const operatType = row.status === 1 ? '停用' : '启用'
      this.$confirm(`您确定要${operatType}用户"${row.roleName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        isUseRole(params).then(res => {
          if (res.code === '0000') {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getTableList(false)
            this.$store.dispatch('api/getRoleList')
          }
        }).catch(error => {
          this.$message.error(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    deleteItem(row) {
      this.$confirm(`您确定要删除角色"${row.roleName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole({ roleId: row.roleId }).then(res => {
          if (res.code === '0000') {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getTableList(false)
          }
        }).catch(error => {
          this.$message.error(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    help() {
      this.$alert(`
        1、角色代表操作权限和数据权限，操作权限是指具有该角色的用户是否能查看、新增、编辑、删除某些数据，数据权限是指具有该角色的用户能操作的数据的范围；</br>
        2、超级管理员的权限是系统默认的最大权限的角色，不能修改；</br>
        3、需要删除角色时必须先清除该角色下的所有成员；</br>
      `, '帮助说明', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    },
    // 页码改变
    handleSizeChange(val) {
      this.pageSize = val
      this.getTableList(false)
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableList(false)
    }

  }
}
</script>
<style lang="scss" scoped>

</style>
